import VueCookie from 'vue-cookie'

const CookieKeys = {
  UserAccount: 'UserAccount'
}

class Session {
  constructor () {
    this.token = ''
    this.init()
  }

  init () {
    const cookieStr = VueCookie.get(CookieKeys.UserAccount) || ''
    if (cookieStr) {
      const token = cookieStr.split('&').find(i => i.startsWith('access_token='))
      if (token) {
        this.token = token.split('=')[1] || ''
      }
    }
  }

  /**
   * 设置token（用于测试）
   * @param data
   */
  set (data) {
    VueCookie.set(CookieKeys.UserAccount, 'access_token=' + data.access_token, { expires: data.expires + 's' })
    this.token = data.access_token
  }

  clear () {
    this.token = ''
    VueCookie.delete(CookieKeys.UserAccount)
  }
}

export default {
  install (Vue, options) {
    const session = new Session()
    Vue.prototype.$cookie = VueCookie
    Vue.mixin({
      created () {
        this.$session = session
      }
    })
  }
}
